//
//  NavigationBarModifier.swift
//  GoCash
//
//  Created by jie on 2024/5/13.
//

import SwiftUI

struct NavigationBarModifier: ViewModifier {
        
    var backgroundColor: UIColor?
    var backColor: Color?
    
    init( backgroundColor: UIColor?) {
        self.backgroundColor = backgroundColor
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithTransparentBackground()
        coloredAppearance.backgroundColor = .clear
        coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
        
        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
        UINavigationBar.appearance().tintColor = .white

    }
    
    func body(content: Content) -> some View {
        ZStack{
            content
            VStack {
                GeometryReader { geometry in
                    Color(self.backgroundColor ?? .clear)
                        .frame(height: geometry.safeAreaInsets.top)
                        .edgesIgnoringSafeArea(.top)
                    Spacer()
                }
            }
        }
    }
}

extension View {
    
    func navigationBarUIColor(_ backgroundColor: Color?) -> some View {
        self.modifier(NavigationBarModifier(backgroundColor: UIColor(backgroundColor!)))
    }

}



struct DefaultNavigationView: ViewModifier {
    
    @Environment(\.presentationMode) var presentationModel
    
    var title: String = ""
    var whiteType: Bool = true
    var leading: (any View)? = nil
    var trailing: (any View)? = nil
    var itemAction: ((Int) -> Void)? = nil
    
    init(title: String, whiteType: Bool, leading: (any View)? = nil, trailing: (any View)? = nil, itemAction: ((Int) -> Void)? = nil) {
        self.title = title
        self.whiteType = whiteType
        self.leading = leading
        self.trailing = trailing
        self.itemAction = itemAction
    }
    
    func body(content: Content) -> some View {
        content
            .navigationBarTitle(Text(title)/*.foregroundColor(COLOR_312A31).font(Font.system(size: 18, weight: .bold))*/, displayMode: .inline)
            .navigationBarUIColor(whiteType ? .white : COLOR_F8F7FE)
            .navigationBarBackButtonHidden()
            .navigationBarItems(leading: AnyView(leadingButton()), trailing: AnyView(tradingView()))
    }
    
    func leadingButton() -> any View {
        if leading != nil { return leading! }
        return Button {
            itemAction==nil ? presentationModel.wrappedValue.dismiss() : itemAction?(1)
        } label: {
            Image(systemName: "chevron.backward.circle.fill").foregroundColor(whiteType ? MAIN_COLOR : MAIN_COLOR).padding(0)
        }
    }
    
    func tradingView() -> any View {
        if trailing != nil { return trailing! }
        return EmptyView()
    }
}


extension View {
    func navigationStyle(
        title: String = "",
        whiteType: Bool = true,
        leading: (any View)? = nil,
        trailing: any View = EmptyView(),
        itemAction: ((Int) -> Void)? = nil
    ) -> some View {
        self.modifier(DefaultNavigationView(
            title: title,
            whiteType: whiteType,
            trailing: trailing,
            itemAction: itemAction
        ))
    }
}













//导航管理器
//private class NavigationLinkManager: ObservableObject{
//    static var shared = NavigationLinkManager()
//    
//    @Published var destinations: [NavigationLinkSource] = []
//    
//    class func push(destination: String, isActive: Binding<Bool>) {
//        NavigationLinkManager.shared.destinations.append(
//            NavigationLinkSource(
//                destinationString: destination, isActive: isActive, index: NavigationLinkManager.shared.destinations.count
//        ))
//    }
//    
//    class func dismiss() {
//        if NavigationLinkManager.shared.destinations.count == 0 { return }
//        NavigationLinkManager.shared.destinations.removeLast()
//    }
//    
//    class func dismissToRoot() {
//        if NavigationLinkManager.shared.destinations.count == 0 { return }
//        NavigationLinkManager.shared.destinations[0].isActive.wrappedValue.toggle()
//        NavigationLinkManager.shared.destinations.removeAll()
//    }
//    
//    class func dissmissTo(viewName: String) {
//        let sources = NavigationLinkManager.shared.destinations
//        for i in 0..<sources.count {
//            let source = sources[i]
//            if source.destinationString == viewName {
//                NavigationLinkManager.shared.destinations[i].isActive.wrappedValue.toggle()
//                print(NavigationLinkManager.shared.destinations[i].isActive.wrappedValue)
//                
//                NavigationLinkManager.shared.destinations.removeAll { s in
//                    return s.index > source.index && s.index <= sources.last!.index
//                }
//                
//                break
//            }
//        }
//    }
//    
//    class func source(viewName: String) -> NavigationLinkSource {
//        for i in 0..<NavigationLinkManager.shared.destinations.count {
//            let source = NavigationLinkManager.shared.destinations[i]
//            if source.destinationString == viewName {
//                return source
//            }
//        }
//        return NavigationLinkSource(destinationString: viewName, isActive: .constant(true), index: 0)
//    }
//    
////    class func sourcesIndex(max: Bool) -> Int {
////        var sources = NavigationLinkManager.shared.destinations
////        if sources.count == 0 { return 0 }
////        sources.sort { s1, s2 in
////            return s1.index < s2.index
////        }
////        
////        return max ? sources.last!.index : sources.first!.index
////    }
//}
//
//
//private struct NavigationLinkSource {
//    var destinationString: String
//    var isActive: Binding<Bool>
//    var index: Int
//}
//
//
//extension NavigationLink where Label == Text {
//    
//    static func dismissTo(viewName: String) {
//        NavigationLinkManager.dissmissTo(viewName: viewName)
//    }
//    
//    static func dismissToRoot() {
//        NavigationLinkManager.dismissToRoot()
//    }
//    
//    @discardableResult
//    static func push(destination: Destination, isActive: Binding<Bool>) -> NavigationLink {
//        let viewName = String(describing: type(of: destination))
//        print("push: \(viewName)")
//        NavigationLinkManager.push(destination: viewName, isActive: isActive)
//        let source = NavigationLinkManager.source(viewName: viewName)
//        
//        //该方法属于预加载模式，页面一进入，就会将destination加入到页面f
//        return NavigationLink("", destination: destination, isActive: source.isActive)
//    }
//}
//
//
//struct NavigationTestView1: View {
//    
//   @State var active = false
//    
//    var body: some View {
//        NavigationView {
//            VStack {
//                NavigationLink.push(destination: NavigationTestView2(), isActive: $active)
//                
//                
//                
//                Button {
//                    active = true
//                } label: {
//                    Text("To NavigationTestView2")
//                }
//            }
//            .navigationStyle(title: "NavigationTestView1")
//        }
//    }
//}
//
//
//struct NavigationTestView2: View {
//    
//    @State var active: Bool = false
//    
//    var body: some View {
//        VStack {
//            NavigationLink.push(destination: NavigationTestView3(), isActive: $active)
//            
//            
//            Button {
//                active.toggle()
//            } label: {
//                Text("To NavigationTestView3")
//            }
//        }
//        
//        
//        .navigationStyle(title: "NavigationTestView2")
//        
//        
//    }
//}
//
//struct NavigationTestView3: View {
//    
//    @State var active: Bool = false
//    
//    var body: some View {
//        VStack {
//            NavigationLink.push(destination: NavigationTestView4(), isActive: $active).padding(0)
//            
//            Button {
//                active.toggle()
//            } label: {
//                Text("To NavigationTestView4")
//            }
//        }
//        
//        
//        .navigationStyle(title: "NavigationTestView3")
//        
//        
//    }
//}
//
//struct NavigationTestView4: View {
//    var body: some View {
//        Button {
//            NavigationLinkManager.dismissToRoot()
////            NavigationLink<Text, EmptyView>.dismissTo(viewName: "NavigationTestView2")
//        } label: {
//            Text("Back to NavigationTestView2")
//        }
//
//        .navigationStyle(title: "NavigationTestView4")
//    }
//}
//
//#Preview(body: {
//    NavigationTestView1()
//})
